// 修缮问题反馈弹窗
<template>
  <div class="addDialog" v-dialogDrag>
    <el-dialog custom-class="small-padding-dialog" :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="70%" @close="handleClosed">
      <div class="dialogWrap">
        <el-form ref="dialogForm" :rules="type == 'approval' ? approvalRules: rules" :model="formData">
          <el-col :span="24">
            <h4 class="dialogItemTitle">修缮问题上报信息</h4>
          </el-col>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="上报人" class="full" prop="initiator">
                <el-input v-halfCharCode v-model="formData.initiator" maxlength="20" :readonly="isReadonly" placeholder="请输入上报人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报时间" class="full" prop="initiateTime">
                <el-date-picker v-model="formData.initiateTime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd" type="datetime" placeholder="请选择上报时间" :readonly="isReadonly" :picker-options="pickerOptions" />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="listFormItem">
              <el-button class="add" size="mini" type="primary" @click="chooseProperty" v-if="!isReadonly">选择物业</el-button>
              <el-form-item label="物业名称" prop="propertyName">
                <el-input v-halfCharCode v-model="formData.propertyName" readonly placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="问题描述" class="full" prop="problemDesc">
                <el-input v-halfCharCode v-model="formData.problemDesc" type="textarea" :readonly="isReadonly" placeholder="请输入内容" maxlength="200" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" class="full" prop="remarks">
                <el-input v-halfCharCode v-model="formData.remarks" type="textarea" :readonly="isReadonly" :placeholder="isReadonly ? '暂无内容' : '请输入内容'" maxlength="200" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 附件 -->
          <el-row :gutter="20" class="album" v-if="dialogVisible">
            <el-col :span="24">
              <h4 class="dialogItemTitle">上传附件</h4>
            </el-col>
            <el-col :span="24">
              <v-upload ref="upload" :busId="formData.billId" modelType="repairQuestion" @onSuccess="onSuccess" v-model="uploadFileList" :isView="['preview','approval'].includes(type)" :canDelete="['add','edit'].includes(type)" />
            </el-col>
          </el-row>

          <!-- 审批 -->
          <el-row v-if="type === 'approval'">
            <el-col :span="24">
              <h4 class="dialogItemTitle">修缮审批</h4>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审批结果" class="full" prop="result">
                <el-radio-group v-model="formData.result">
                  <el-radio label="1">同意</el-radio>
                  <el-radio label="0">不同意</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="type === 'preview'">
              <el-form-item label="审批人" class="full" prop="approvePerson">
                <el-input v-halfCharCode v-model="formData.approvePerson" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="审批意见" class="full" prop="approveContent">
                <el-input v-halfCharCode v-model="formData.approveContent" maxlength="200" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 审批查看 -->
          <el-table :data="approvalList" style="width: 100%" v-if="type !== 'add'">
            <el-table-column align="left" prop="approvePerson" label="审批人" width="160" />
            <el-table-column align="left" prop="approveTm" label="审批时间" width="160" />
            <el-table-column align="left" label="审批结果" width="160">
              <template slot-scope="scope">{{getStatusName(scope.row.approveStatus)}}</template>
            </el-table-column>
            <el-table-column align="left" prop="approveContent" label="审批意见" />
          </el-table>
        </el-form>

        <!-- 物业选择弹窗 -->
        <propertyChooseDialog ref="propertyChoose" dialogType="question" @changeProperty="handlePropertyChange" />
      </div>
      <div slot="footer">
        <!--<el-button @click="$bus.$emit('operationLog',formData.billId)" v-if="type==='preview'">操作日志</el-button>-->
        <el-button v-if="type !== 'preview'" type="primary" @click="save">{{type == 'approval' ? '审 批':'提 交'}}</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import moment from 'moment';

import { changeQuestion, approvalQuestion, getApproveInfo, getUploadFiles } from "@/views/wy-operate/api/repair.js";
export default {
  name: "addDepartment",
  components: {
    propertyChooseDialog
  },
  inject: ['initList'],
  data () {
    return {
      //弹窗类型，默认新增
      type: "add",
      //选中的物业
      radioId: "",
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        billId: "",
        // 房源ID
        roomId: "",
        // 上报人
        initiator: "",
        // 上报时间
        initiateTime: "",
        // 物业名称
        propertyName: "",
        // 问题描述
        problemDesc: "",
        // 备注
        remarks: "",
        // 物业类型
        propertyType: ''
      },
      // 审批表单
      approvalForm: {
        // 审批结果
        result: '',
        // 审批内容
        approveContent: "",
        // 审批人
        approvePerson: "",
        // 审批时间
        approveTm: "",
      },
      // 审批记录
      approvalList: [],
      // 上传文件列表
      uploadFileList: [],
      // 校验
      rules: {
        initiator: [{ required: true, message: "上报人不能为空", trigger: "blur" }],
        initiateTime: [{ required: true, message: "上报时间不能为空", trigger: "blur" }],
        propertyName: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
        problemDesc: [{ required: true, message: "问题描述不能为空", trigger: "blur" }],
      },
      // 审批校验
      approvalRules: {
        initiator: [{ required: true, message: "上报人不能为空", trigger: "blur" }],
        initiateTime: [{ required: true, message: "上报时间不能为空", trigger: "blur" }],
        propertyName: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
        problemDesc: [{ required: true, message: "问题描述不能为空", trigger: "blur" }],
        result: [{ required: true, message: "审批结果不能为空", trigger: "blur" }],
        approvePerson: [{ required: true, message: "审批人不能为空", trigger: "blur" }],
        approveContent: [{ required: true, message: "审批意见不能为空", trigger: "blur" }],
      },
      pickerOptions: {
        disabledDate: function disabledDate (time) {
          //return time.getTime() < Date.now() // 选当前时间之后的时间
          return time.getTime() > Date.now() // 选当前时间之前的时间
        }
      }
    }
  },
  computed: {
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增",
        approval: "审批",
      }[this.type];
    },
    // 判断是否只读
    isReadonly () {
      return ["preview", "approval"].includes(this.type);
    },
  },
  methods: {
    //开启弹窗
    async show ({ type, data = {} }) {
      if (['preview', 'edit', 'approval'].includes(type)) {
        const res = await this.http(`/api/repairbill/${data.billId}`)
        this.formData = type === 'approval' ? { ...this.formData, ...this.approvalForm, ...res.data.data } : { ...this.formData, ...res.data.data };
        this.$nextTick(() => {
          this.$refs.upload && this.$refs.upload.getFiles(data.billId)
        })
        // 获取审批结果信息
        data.billStatus && this.getStatus(data.billId)
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 获取审批相关信息
    getStatus (billId) {
      getApproveInfo(billId).then(res => {
        const { records } = res.data.data
        if (records.length) {
          this.approvalForm = {
            ...records[0],
            result: this.formData.billStatus == 11 ? '1' : '0'
          }
        }
        this.approvalList = records
      })
    },
    // 提交新增
    async save () {
      try {
        const valid = await this.$refs.dialogForm.validate();
        if (!valid) return;
        if (this.type === 'approval') {
          let { result, approveContent, approvePerson } = this.formData;
          let params = {
            approveContent,
            approvePerson,
            approveTm: moment().format('YYYY-MM-DD hh:mm:ss'),
            billId: this.formData.billId,
          }
          approvalQuestion(params, result).then((res) => {
            if (res.data.code == 0) {
              this.$message.success(`${this.dialogTitle}成功!`);
              this.initList({ keyword: '', current: 1 })
              this.dialogVisible = false;
            } else {
              this.$message.error(res.data.msg)
            }
          });
        } else {
          this.$refs.upload.submit('repairQuestion', this.formData.billId);
        }
      } catch (error) {
        //console.log(error)
      }

    },
    // 上传成功
    async onSuccess (response, file, fileList) {
      let params = this.type == 'add' ? { ...this.formData, billId: response.data } : this.formData
      const res = await changeQuestion(params, this.type)
      if (res.data.code == 0) {
        this.$message.success(`${this.dialogTitle}成功!`);
        this.initList({ keyword: '', current: 1 })
        this.dialogVisible = false;
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 选择物业名称
    chooseProperty () {
      this.$refs.propertyChoose.show("question");
    },
    // 监听物业改变
    handlePropertyChange (data) {
      this.formData = {
        ...this.formData,
        address: data.address,
        propertyName: data.propertyName,
        roomId: data.roomId,
        propertyType: data.propertyType
      };
    },
    // 获取审批状态名称
    getStatusName (status = this.formData.billId) {
      return {
        '10': '待审核',
        '11': '待审核',
        '12': '审核通过',
        '13': '审核不通过',
        '14': '验收通过',
        '15': '验收未通过'
      }[status] || ''
    },
    // 弹窗关闭还原
    handleClosed () {
      this.uploadFileList = []
      let _formData = JSON.parse(JSON.stringify(this.formData))
      let _approvalForm = JSON.parse(JSON.stringify(this.approvalForm))
      for (let i in _formData) {
        _formData[i] = ''
      }
      for (let i in _approvalForm) {
        _approvalForm[i] = ''
      }
      this.formData = _formData
      this.approvalForm = _approvalForm
      this.approvalList = []
      this.$refs.dialogForm.resetFields()
    }

  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-date-editor--datetime {
    width: 100%;
  }
  .album {
    .el-col {
      margin-bottom: 20px;
    }
    .img {
      width: 100%;
      height: 200px;
    }
  }
}
</style>
